package com.qfedu.hotelssm.service.impl;

import com.qfedu.hotelssm.dao.UserDao;
import com.qfedu.hotelssm.entity.User;
import com.qfedu.hotelssm.service.intf.UserService;
import com.qfedu.hotelssm.util.PassUtils;
import com.qfedu.hotelssm.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Objects;

import static com.qfedu.hotelssm.config.SystemConfig.*;

/**
 * @author truman
 * @date 2022/8/31
 * @description
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao dao;

    @Override
    public R save(User user) {
        user.setPassword(PassUtils.aesenc(AES_KEY,user.getPassword()));
        if (dao.save(user) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R delete(int id) {
        if (dao.delete(id) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R update(User user) {
        if (dao.update(user) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R selectByName(String username) {
        User user = dao.selectByName(username);
        if (Objects.nonNull(user)) {
            return R.fail();
        } else {
            return R.ok();
        }
    }

    @Override
    public R login(User user, HttpSession session) {
        User user1 = dao.selectByName(user.getUsername());
        if (Objects.nonNull(user1)) {
            String pwd = PassUtils.aesdec(AES_KEY, user1.getPassword());
            if (Objects.equals(user.getPassword(),pwd)) {
                session.setAttribute("user",user1);
                return R.ok();
            }
        }
        return R.fail("用户名或密码错误！");
    }
}
